package com.monkey.netty.chapter1;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * BIO服务端
 * 
 * @author monkeychen
 */
public class BioServer {

	private static ServerSocket serverSocket;

	public static void main(String[] args) throws IOException {
		serverSocket = new ServerSocket(8888);
		System.out.println("服务端启动成功!");
		while (true) {
			// 1、等待客户端连接，此处会阻塞
			Socket socket = serverSocket.accept();
			new Thread(new Runnable() {

				@Override
				public void run() {
					System.out.println("有客户端连接成功!");
					try {
						InputStream is = socket.getInputStream();
						byte[] bytes = new byte[1024];
						while (true) {
							// 2、读取客户端数据，如果没有数据或者数据没有读取完毕，此处会阻塞
							int data = is.read(bytes);
							if (data != -1) {
								String info = new String(bytes, 0, data, "GBK");
								System.out.println(info);
							} else {
								break;
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}).start();
		}
	}

}
